package com.example.dragon.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.example.dragon.untis.DateUtils;
import com.example.dragon.untis.MyToast;
import com.example.dragon.untis.ToastUtil;
import com.example.dragon.xmf.ConfirmOrderActivity;
import com.example.dragon.xmf.MapActivity;
import com.example.dragon.xmf.R;
import com.github.florent37.singledateandtimepicker.dialog.SingleDateAndTimePickerDialog;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Pattern;

public class OrderFragment extends Fragment {

    private Button msubBtn;
    private LinearLayout mDateLinear,mfee_layout;
    private RelativeLayout maddresLayout;
    private TextView mdateText,mfeeText,maddressText;
    private String mFeeStr="0";
    private String mattentionStr="";
    private String mremindStr="";
    private String mdateStr;
    private RelativeLayout mattionRelatv,mremidRlatv;
    private EditText mnameEdit,mtelEdit;
    SimpleDateFormat simpleDateFormat;
    SingleDateAndTimePickerDialog.Builder singleBuilder;
    public AMapLocationClient mLocationClient = null;
    public AMapLocationClientOption mLocationOption = null;
    public  String ADDRESS="",lng,lat;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = LayoutInflater.from(getContext()).inflate(R.layout.fragment_order,null);
        initControls(view);
        initLocation();
        return view;
    }

    private void initControls(View view){
        mnameEdit = (EditText)view.findViewById(R.id.nameEdit);
        mtelEdit = (EditText)view.findViewById(R.id.telEdit);
        msubBtn = (Button)view.findViewById(R.id.submitBtn);
        mDateLinear = (LinearLayout)view.findViewById(R.id.update_time);
        mdateText = (TextView)view.findViewById(R.id.date_text);
        mfee_layout = (LinearLayout)view.findViewById(R.id.fee_linear);
        mfeeText = (TextView)view.findViewById(R.id.fee_text);
        mattionRelatv =(RelativeLayout)view.findViewById(R.id.attention_relat);
        mremidRlatv = (RelativeLayout)view.findViewById(R.id.remind_relat);
        maddresLayout = (RelativeLayout)view.findViewById(R.id.orderAdressRelat);
        maddressText = (TextView)view.findViewById(R.id.oradressText);
//        ToastUtil.show(getContext(),ADDRESS);
        maddresLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivityForResult(new Intent(getContext(), MapActivity.class),0);
            }
        });
        msubBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SubmitOrder();
            }
        });
        mfee_layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDialog();
            }
        });
        mDateLinear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                simpleClicked();
            }
        });
        mattionRelatv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditAttention("1");
            }
        });
        mremidRlatv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditAttention("2");
            }
        });
        this.simpleDateFormat = new SimpleDateFormat("yyyy年MM月dd日HH时", Locale.getDefault());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("Mapaddress","data"+data);
        switch (requestCode){
            case 0:
                //Log.i("Mapaddress","data"+data.toString());
                if (data!=null){
                    Log.i("Mapaddress","data"+data.toString());
                    String Mapaddress = data.getExtras().getString("Mapaddress");
                    lng = data.getExtras().getString("lng");
                    lat = data.getExtras().getString("lat");
                    Log.i("Mapaddress",lat+"Mapaddress:"+Mapaddress);
                    if(Mapaddress != "") {
                        ADDRESS= data.getExtras().getString("Mapaddress");
                        maddressText.setText(Mapaddress);
                    }
                }
                break;
        }
    }

    private void initLocation(){
        mLocationOption = new AMapLocationClientOption();
        mLocationClient = new AMapLocationClient(getContext());
        mLocationClient.setLocationListener(mLocationListener);
        mLocationOption = new AMapLocationClientOption();
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        // mLocationOption.setInterval(1000);
        mLocationOption.setNeedAddress(true);
        mLocationOption.setOnceLocation(true);
        mLocationOption.setWifiActiveScan(false);
//        mLocationOption.setHttpTimeOut(20000);
        mLocationOption.setLocationCacheEnable(false);
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {
        @Override
        public void onLocationChanged(AMapLocation aMapLocation) {
            if (aMapLocation != null) {
                if (aMapLocation.getErrorCode() == 0) {
                    ADDRESS=aMapLocation.getCity()+aMapLocation.getDistrict()+aMapLocation.getStreet()+aMapLocation.getStreetNum()+"";
                    maddressText.setText(ADDRESS);
                    lat = aMapLocation.getLatitude()+"";
                    lng = aMapLocation.getLongitude()+"";
                }else {
                    //定位失败时，可通过ErrCode（错误码）信息来确定失败的原因，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError","location Error, ErrCode:"
                            + aMapLocation.getErrorCode() + ", errInfo:"
                            + aMapLocation.getErrorInfo());
                }
            }
        }
    };

    private void SubmitOrder(){
        String name = mnameEdit.getText().toString();
        String tel = mtelEdit.getText().toString();
        if (mdateText.getText().toString().equals("现在")){
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy年MM月dd日 HH时");
            Date curDate = new Date(System.currentTimeMillis());//获取当前时间
            String dates = formatter.format(curDate);
            long dats = DateUtils.getStringToDate(dates);
            mdateStr = dates;
          //  ToastUtil.show(getContext(),dats+"----111");
        }else {
            String date = mdateText.getText().toString();
            //long dats = DateUtils.getStringToDate(date);
            mdateStr = date;
           // ToastUtil.show(getContext(),date+"----222");
        }
        if (name.equals("") || tel.equals("")){
            new MyToast(getContext(),"请输入完整信息",2);
        }else {
            if(matchPhone(tel)){
                new MyToast(getContext(),"提交",2);
                Intent intent = new Intent(getContext(), ConfirmOrderActivity.class);
                intent.putExtra("name",name);
                intent.putExtra("worktime",mdateStr);
                intent.putExtra("mobile",tel);
                intent.putExtra("address",maddressText.getText());
                intent.putExtra("fee",mFeeStr);
                intent.putExtra("matter",mattentionStr);
                intent.putExtra("message",mremindStr);
                intent.putExtra("lng",lng);
                intent.putExtra("lat",lat);
                startActivity(intent);
            }else {
                new MyToast(getContext(),"手机号各式不正确",2);
            }

        }
    }

    private void simpleClicked(){
        final Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.MONTH, 0);
        calendar.set(Calendar.YEAR, 2017);
        final Date minDate = calendar.getTime();

        calendar.set(Calendar.DAY_OF_MONTH, 5);
        final Date maxDate = calendar.getTime();

        calendar.set(Calendar.DAY_OF_MONTH, 2);
        final Date defaultDate = calendar.getTime();

        singleBuilder = new SingleDateAndTimePickerDialog.Builder(getContext())
                .bottomSheet()
                .curved()

                .backgroundColor(Color.WHITE)
                .mainColor(Color.GRAY)
                .defaultDate(defaultDate)
                .minDateRange(minDate)
                .maxDateRange(maxDate)

                .title("Simple")
                .listener(new SingleDateAndTimePickerDialog.Listener() {
                    @Override
                    public void onDateSelected(Date date) {
//                        int year = date.getYear();
//                        int month= date.getMonth()+1;
//                        int day = date.getDate();
//                        int hours = date.getHours();
//                        String mon="",hour="";
//                        if (month<10){
//                            mon="0"+month;
//                        }
//                        if (hours<10){
//                            hour="0"+hours;
//                        }
//                        String dates =mon+"月-"+
//                                day+"日-"+
//                                hour+"时";
                        mdateText.setText(simpleDateFormat.format(date));
                        Log.i("firstDate","");
                    }
                });
        singleBuilder.display();
    }

    public void EditAttention(final String flag){
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        final View layout = inflater.inflate(R.layout.attention_layout, null);//获取自定义布局
        final EditText attEdit = (EditText)layout.findViewById(R.id.att_Edit);
        if (flag.equals("1")){
            builder.setTitle("注意事项");
            if (("").equals(mattentionStr)){
            }else {
                attEdit.setText(mattentionStr);
            }
        }else {
            builder.setTitle("给司机捎句话");
            if (("").equals(mremindStr)){
            }else {
                attEdit.setText(mremindStr);
            }
        }
        builder.setView(layout);
        // builder.setIcon(R.drawable.ic_launcher);//设置标题图标
        //设置标题内容
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                if (flag.equals("1")){
                    mattentionStr = attEdit.getText().toString();
                }else {
                    mremindStr = attEdit.getText().toString();
                }
            }
        });
        //取消
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub

            }
        });
        final AlertDialog dlg = builder.create();
        dlg.show();
    }

    public void showDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        LayoutInflater inflater = getActivity().getLayoutInflater();
        final View layout = inflater.inflate(R.layout.fee_layout, null);//获取自定义布局
        RadioGroup radioGroup = (RadioGroup)layout.findViewById(R.id.fee_radio_group);
        final EditText feeEdit = (EditText)layout.findViewById(R.id.fee_Edit);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup radioGroup, int i) {
                switch (i){
                    case R.id.first_rb:
                        mFeeStr=10+"";
                        break;
                    case R.id.two_rb:
                        mFeeStr=20+"";
                        break;
                    case R.id.three_rb:
                        mFeeStr=50+"";
                        break;
                }
            }
        });
        builder.setView(layout);
        // builder.setIcon(R.drawable.ic_launcher);//设置标题图标
        builder.setTitle("");//设置标题内容
        builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub
                Toast.makeText(getContext(), "ok", Toast.LENGTH_SHORT).show();

                if ((feeEdit.getText().toString()).equals("")){
                    mfeeText.setText(mFeeStr);
                }else {
                    mFeeStr=feeEdit.getText().toString();
                    mfeeText.setText(mFeeStr);

                }
            }
        });
        //取消
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                // TODO Auto-generated method stub

            }
        });
        final AlertDialog dlg = builder.create();
        dlg.show();
    }
    private boolean matchPhone(String text) {
        if (Pattern.compile("^((1[358][0-9])|(14[57])|(17[0678]))\\d{8}$").matcher(text).matches()) {
            return true;
        }
        return false;
    }
}
